package com.demo.connectdbtest.module.price.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSONObject;
import com.demo.connectdbtest.module.common.util.DateUtils;
import com.demo.connectdbtest.module.price.domain.Price;
import com.demo.connectdbtest.module.price.domain.Resource;
import com.demo.connectdbtest.module.price.popoMapper.PriceMapper;
import com.demo.connectdbtest.module.price.popoMapper.ResourceMapper;
import com.demo.connectdbtest.module.price.popoMapper.StudentMapper;
import com.demo.connectdbtest.module.price.vo.AddPriceVo;
import com.demo.connectdbtest.module.price.vo.StudentVO;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author
 * @Date 10:46 2021/12/20
 * @Description
 */

@RestController
@RequestMapping("/price")
public class PriceController {

    private static final Logger log = LoggerFactory.getLogger(PriceController.class);

    @Autowired
    private PriceMapper priceMapper;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("/getNumberScale")
    public String getNumberScale() {
        Price price = null;
        try {
            price = priceMapper.getNumberScale();
            log.info("从库里面获取的数据data={}", price);
        } catch (Exception e) {
            return "fail";
        }
        return price.toString();
    }

    @GetMapping("/getAllPrice")
    public String getAllPrice() {
        List<BigDecimal> priceList = null;
        try {
            priceList = priceMapper.getAllPrice();
            log.info("从库里面获取的数据data={}", JSONObject.toJSONString(priceList));
        } catch (Exception e) {
            log.debug(JSONObject.toJSONString(e));
            return "fail" + JSONObject.toJSONString(e);
        }
        return JSONObject.toJSONString(priceList);
    }

    @PostMapping("/update")
    public String updatePrice(@RequestBody AddPriceVo vo) {
        try {
            priceMapper.updatePrice(vo.getId(), vo.getPrice());
            log.info("从库里修改的数据data={}", vo.getId());
        } catch (Exception e) {
            log.debug(JSONObject.toJSONString(e));
            return "update fail" + JSONObject.toJSONString(e);
        }
        return "successs-update" + vo.toString();
    }

    @PostMapping("/add")
    public AddPriceVo addPrice(@RequestBody AddPriceVo vo) {
        try {
            priceMapper.addPrice(vo);
            log.info("添加的数据data={}", vo.getPrice());
        } catch (Exception e) {
            log.debug(JSONObject.toJSONString(e));
            return vo;
        }
        return vo;
    }

    @PostMapping("/delete")
    public String deletePrice(@RequestBody Integer id) {
        try {
            priceMapper.deletePrice(id);
            log.info("从库里删除的数据data={}", id);
        } catch (Exception e) {
            log.debug(JSONObject.toJSONString(e));
            return "fail" + JSONObject.toJSONString(e);
        }
        return "successs";
    }


    @GetMapping("/batchUpdate")
    public String batchUpdate() {
        Price price = null;
        try {
            Price price1 = new Price();
            price1.setId(1);
            price1.setPrice(new BigDecimal("5"));
            price1.setNumber(5);
            Price price2 = new Price();
            price2.setId(2);
            price2.setPrice(new BigDecimal("6"));
            price2.setNumber(6);
            ArrayList<Price> prices = new ArrayList<>();
            prices.add(price1);
            prices.add(price2);
            priceMapper.batchUpdate(prices);
            log.info("批量更新的的数据data={}", price2);
        } catch (Exception e) {
            log.error("批量更新的的数据data error={}", e);
            return "fail";
        }
        return "ok";
    }

    /*
    *
    * [
    {"2022@6":["01","02"]},
    {"2022@7":["01","02"]},
    {"2022@8":["01","02"]}
    ]
    *
    * List<Map<String,List<String>>> dateStr
    * */
    @ApiOperation(value = "提现日设置")
    @PostMapping(value = "/withdrawDay/add")
    public String addWithdrawDay(@RequestParam List<Object> dateStr) {
        log.debug("提现日设置设置添加的参数dateStr={}", JSONObject.toJSONString(dateStr));
//        List<SetWithdrawDayReqParams> list = new ArrayList<>();
//        dateStr.forEach(item->{
//            Set<Map.Entry<String, List<String>>> entries = item.entrySet();
//            Iterator<Map.Entry<String, List<String>>> iterator = entries.iterator();
//            while (iterator.hasNext()) {
//                Map.Entry<String, List<String>> next = iterator.next();
//                List<String> day = next.getValue();
//                String month = next.getKey();
//                SetWithdrawDayReqParams addItem = new SetWithdrawDayReqParams();
//                addItem.setDay(day);
//                addItem.setMonth(month);
//                list.add(addItem);
//            }
//        });
        //[{"month":"2022@5","day":["01","12"]},{"month":"2022@6","day":["15","52"]}]
//        log.debug("final接受参数={}",JSONObject.toJSONString(list));
        return JSONObject.toJSONString(dateStr);
    }

    public static List<Long> listRedPointByMonthKey(String monthKey, List<String> dayStrList) {
        ArrayList<Long> respList = new ArrayList<>();

        //获取日期
//        String days = "[\"01\",\"05\",\"09\",\"16\",\"23\"]";
//        List<String> dayStrList = JSONObject.parseArray(days, String.class);
        dayStrList.forEach(item -> {
            System.out.println(item + "++++");
        });
        String[] split = monthKey.split("@");
        String year = split[0];
        String m = split[1];
        String month = Integer.valueOf(m) > 9 ? m : "0" + m;
        System.out.println("分割日期year={},month={},m={}" + year + "-----" + month + "-----" + m);
        List<String> dateList = new ArrayList<>();
        dayStrList.forEach(item -> {
            dateList.add(year + "-" + month + "-" + item);
        });
        System.out.println("最终返回的提现日dateList={}" + JSONObject.toJSONString(dateList));
        if (!CollectionUtils.isEmpty(dateList)) {
            dateList.forEach(date -> {
                long time = DateUtils.parase(date, DateUtils.DATEFORMATDAY).getTime();
                respList.add(time);
            });
        }
        return respList;
    }


    @PostMapping("/addPriceConfig")
    public String addPriceConfig(@RequestBody List<Price> list) {
        log.debug("添加数据配置result={}", JSONObject.toJSONString(list));
        return JSONObject.toJSONString(list);

    }

    @GetMapping("/tree/data")
    public String addPriceConfig(@RequestParam(value = "name", required = false) String name) {
        log.debug("树状结构参数={}", JSONObject.toJSONString(name));
        List<Resource> list = new ArrayList<>();
        //所有记录
        List<Resource> tableList = resourceMapper.getAllData();
        list = resourceMapper.selectByCondition(name);


        // 获取所有的一级目录 //根据条件查询出来的list
//        for (Resource table : tableList) {
//            Long parentId = table.getParentId();
//            if (parentId != null && parentId == 0) {
//                list.add(table);
//            }
//        }

        // 获取一级目录的子目录
        for (Resource table : list) {
            table.setChildren(getSubList(table.getId(), tableList));
        }


//        原文链接：https://blog.csdn.net/weixin_42322400/article/details/107669057
        //  resourceMapper.getTreeData(name);
        return JSONObject.toJSONString(list);

    }

    private List<Resource> getSubList(Integer id, List<Resource> list) {
        List<Resource> chirdList = new ArrayList<>();

        // 子目录下的直接子目录
        for (Resource table : list) {
            Integer parentId = Integer.valueOf(String.valueOf(table.getParentId()));
            if (parentId != null && parentId.equals(id)) {
                chirdList.add(table);
            }
        }

        // 子数据的间接子目录
        for (Resource table : chirdList) {
            table.setChildren(getSubList(table.getId(), list));
        }

        // 递归结束条件，子目录数量为0
        if (chirdList.size() == 0) {
            return chirdList;
        }

        return chirdList;
    }


//    @ApiOperation("将查中的数据导出到excel")
//    @RequestMapping("export")
//    public void exportDataToExcel() throws IOException {
//        QueryWrapper<StudentVO> queryWrapper = new QueryWrapper<>();
//        queryWrapper.like("name","h");
//        List<StudentVO> list = studentService.list(queryWrapper);
//        ExportParams exportParams = new ExportParams("用户列表","第一页");
//        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, StudentVO.class, list);
//        // 将工作簿的数据写到指定位置生成表格 web开发可直接将将流输出给前端
//        FileOutputStream fileOutputStream = new FileOutputStream("/home/hurw/Documents/student.xlsx");
//        workbook.write(fileOutputStream);
//        fileOutputStream.close();
//        workbook.close();
//    }

    @ApiOperation("将excel中的数据入库")
    @RequestMapping("/import")
    public void importFromExcel() {
        try {
            ImportParams params = new ImportParams();
//            params.setTitleRows(1);//标题占几行,从哪行开始读取
            params.setHeadRows(1);//header占几行
            FileInputStream fileInputStream = new FileInputStream("C:\\Users\\DELL\\Desktop\\importTest.xlsx");
            List<StudentVO> list = ExcelImportUtil.importExcel(fileInputStream, StudentVO.class, params);
            log.info("导入的数据：{}",JSONObject.toJSONString(list));
            studentMapper.saveBatch(list);
        } catch (Exception e) {
            log.error("发生异常：{}", e);
        }
    }


    //@Autowired
    //private ReportDemoService reportDemoService;
    @GetMapping("/download")
    @SneakyThrows(Exception.class)
    public void download(Long id, HttpServletResponse response, HttpServletRequest request) {
        // 防止日志记录获取session异常
        request.getSession();
        // 设置编码格式
        response.setContentType("application/pdf;charset=UTF-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("调试PDF", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".pdf");
        //reportDemoService.download(id,response);
    }

}
